<template>
	<view class="store_detail_page">
		<u-navbar autoBack fixed placeholder bgColor="#f3f3f3">
			<template #left>
				<view class="navBar">
					<u-icon name="arrow-left" color="#000" size="18"></u-icon>
					<text class="nav_title">{{ form.id ? '修改店铺' : '新增店铺'}}</text>
				</view>
			</template>
		</u-navbar>
    <!--  步骤条  -->
    <view class="steps">
      <view class="step">
        <u-badge numberType="limit" type="primary" value="1"></u-badge>
        <text>{{ form.id ? '编辑店铺' : '添加店铺' }}</text>
      </view>
      <u-icon name="arrow-right"></u-icon>
      <view class="step un_active">
        <u-badge numberType="limit" type="primary" value="2"></u-badge>
        <text>资质认证</text>
      </view>
    </view>
		<scroll-view scroll-y class="content" :style="{ height: `calc(100% - ${navBarHeight}px - 64rpx)` }">
			<view class="card_list">
        <u-form :model="form" :rules="rules" ref="form">
          <view class="card_box">
            <view class="card_title">店铺名称<text>*</text></view>
            <view class="card_content">
              <u-form-item prop="name" labelWidth="0">
                <u-input v-model="form.name" type="text" placeholder="请输入店铺名称"/>
              </u-form-item>
            </view>
          </view>
          <view class="card_box">
            <view class="card_title">店铺类型<text>*</text></view>
            <view class="card_content">
              <view class="with_arrow" @click="showShopType = true">
                <u-form-item prop="shopType.dictLabel" labelWidth="0">
                  <u-input v-model="form.shopType.dictLabel" type="text" disabled disabledColor="#fff" placeholder="请选择店铺类型"/>
                </u-form-item>
                <u-icon name="arrow-right"></u-icon>
              </view>
              <u-picker :show="showShopType" :columns="shopTypeList" key-name="dictLabel" @confirm="confirmShopType" @cancel="showShopType = false"></u-picker>
            </view>
          </view>
          <view class="card_box">
            <view class="card_title title_fuza">
              <view class="title_top">
                <view>地图位置<text>*</text></view>
              </view>
              <view class="title_bottom">位置由误会影响导航，请仔细确认</view>
            </view>
            <view class="card_content">
              <map @click="openMap" style="width: 100%; height: 240rpx; border-radius: 16rpx; overflow: hidden" :latitude="latitude" :longitude="longitude" :markers="markers" />
            </view>
            <view class="card_title" style="margin-top: 32rpx;">地址<text>*</text></view>
            <view class="card_content">
              <u-form-item prop="address" labelWidth="0">
                <u-input v-model="form.address" type="text" placeholder="请输入店铺地址"/>
              </u-form-item>
            </view>
            <u-divider></u-divider>
            <view class="card_title">归属景区<text>*</text></view>
            <view class="card_content">
              <view class="with_arrow" @click="showScenicArea = true">
                <u-form-item prop="scenicArea.jingquName" labelWidth="0">
                  <u-input v-model="form.scenicArea.jingquName" type="text" disabled disabledColor="#fff" placeholder="请选择景区"/>
                </u-form-item>
                <u-icon name="arrow-right"></u-icon>
              </view>
              <u-picker :show="showScenicArea" :columns="scenicAreaList" key-name="jingquName" @confirm="confirmScenicArea" @cancel="showScenicArea = false"></u-picker>
            </view>
          </view>
          <view class="card_box">
            <view class="card_title title_fuza">
              <view class="title_top">
                <view>门脸照片<text>*</text></view>
              </view>
              <view class="title_bottom">建议打开手机定位现场拍摄</view>
            </view>
            <view class="card_content">
              <view class="file_upload">
                <u-form-item prop="frontPhotoList" label-width="0">
                  <u-upload
                    :fileList="form.frontPhotoList"
                    @afterRead="addFrontPhoto"
                    @delete="deleteFrontPhoto"
                    :capture="['camera']"
                    uploadIcon="photo"
                    uploadText="上传门脸照"
                    name="1"
                    :maxCount="1"
                    width="160"
                    height="100"
                  ></u-upload>
                </u-form-item>
              </view>
            </view>
          </view>
          <view class="card_box">
            <view class="card_title title_fuza">
              <view class="title_top" @click="expandBusiness = !expandBusiness">
                <view>营业时间</view>
                <template>
                  <u-icon v-if="expandBusiness" name="arrow-up"></u-icon>
                  <u-icon v-else name="arrow-down"></u-icon>
                </template>
              </view>
              <view v-if="expandBusiness" class="title_bottom">正确的营业时间，可提升店铺到客率</view>
            </view>
            <template v-if="expandBusiness">
              <view class="card_content">
                <view class="add_icon">
                  <u-icon name="plus-circle-fill"></u-icon>
                </view>
                <u-form-item prop="businessTime" label-width="0">
                  <u-input v-model="form.businessTime" type="text" placeholder="添加营业时间" />
                </u-form-item>
              </view>
              <u-divider></u-divider>
              <view class="card_title">营业电话</view>
              <view class="card_content">
                <view class="add_icon">
                  <u-icon name="plus-circle-fill"></u-icon>
                </view>
                <u-form-item prop="businessPhone" label-width="0">
                  <u-input v-model="form.businessPhone" type="text" placeholder="添加营业电话" />
                </u-form-item>
              </view>
            </template>
          </view>
          <view class="card_box">
            <view class="card_title">姓名<text>*</text></view>
            <view class="card_content">
              <u-form-item prop="applyName" label-width="0">
                <u-input v-model="form.applyName" type="text" placeholder="请输入姓名" />
              </u-form-item>
            </view>
            <u-divider></u-divider>
            <view class="card_title">手机号码<text>*</text></view>
            <view class="card_content">
              <u-form-item prop="applyPhone" label-width="0">
                <u-input v-model="form.applyPhone" type="number" placeholder="请输入手机号码" />
              </u-form-item>
            </view>
          </view>
        </u-form>
			</view>
		</scroll-view>
		<view class="footer">
      <u-button type="primary" shape="circle" text="下一步" @click="next"></u-button>
		</view>
	</view>
</template>

<script>
import {uploadImg} from "@/api/system/user";
import {getJingquList, getQiyeDetail} from "@/api/shop";
import {getSystemDictTypeData} from "@/api/system";
import {MERCHANT_TYPE} from "@/utils/enum";

const scope = 'scope.userLocation'
export default {
    async onLoad(option) {
      await this.getQiyeTypeList()
      await this.getJingquList()
      if (option.shopId) {
        // 编辑
        await this.getQiyeDetail(option.shopId)
        return
      }
      this.isGetLocation()
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
		data() {
			return {
        form: {
          // 店铺名称
          name: '',
          // 店铺类型
          shopType: {},
          // 地址
          address: '',
          // 归属景区
          scenicArea: {},
          // 门脸照片
          frontPhotoList: [],
          // 营业时间
          businessTime: '',
          // 营业电话
          businessPhone: '',
          // 姓名
          applyName: '',
          // 手机号码
          applyPhone: ''
        },
        showShopType: false,
        shopTypeList: [[]],
        // 地图位置
        latitude: 39.909,// 默认纬度
        longitude: 116.39742,// 默认经度(北京天安门)
        markers: [{
          id: 110,
          latitude: 39.909,
          longitude: 116.39742,
          iconPath: '/static/img/shop/location_icon.png',
          width: 20,
          height: 20
        }],
        showScenicArea: false,
        scenicAreaList: [[]],
        expandBusiness: true,
        rules: {
          name: {
            type: 'string',
            required: true,
            message: '请填写店铺名称',
            trigger: ['blur', 'change']
          },
          'shopType.dictLabel': {
            type: 'string',
            required: true,
            message: '请选择店铺类型',
            trigger: ['blur', 'change']
          },
          address: {
            type: 'string',
            required: true,
            message: '请填写店铺地址',
            trigger: ['blur', 'change']
          },
          'scenicArea.jingquName': {
            type: 'string',
            required: true,
            message: '请选择归属景区',
            trigger: ['blur', 'change']
          },
          frontPhotoList: {
            type: 'array',
            validator: (rule, value, callback) => {
              console.warn(value, '2222222222')
              return this.form.frontPhotoList.length > 0 && this.form.frontPhotoList[0].status === 'success'
            },
            message: '请上传门脸照片',
            trigger: ['blur', 'change']
          },
          businessPhone: {
            // 自定义验证函数
            validator: (rule, value, callback) => {
              if (!value) return true
              return uni.$u.test.mobile(value);
            },
            message: '手机号码不正确',
            trigger: ['change','blur'],
          },
          applyName: {
            type: 'string',
            required: true,
            message: '请输入申请人姓名',
            trigger: ['blur', 'change']
          },
          applyPhone: [
            {
              type: 'string',
              required: true,
              message: '请输入申请人手机号码',
              trigger: ['blur', 'change']
            },
            {
              // 自定义验证函数
              validator: (rule, value, callback) => {
                return uni.$u.test.mobile(value);
              },
              message: '手机号码不正确',
              trigger: ['change','blur'],
            }
          ]
        }
			}
		},
		computed: {
			navBarHeight () {
				const platform = uni.getSystemInfoSync().platform
				const statusBarHeight = uni.getSystemInfoSync().statusBarHeight
				let navHeight = 0
				if (['ios', 'devtools'].includes(platform)) {
					navHeight = 44
				} else {
					navHeight = 48
				}
				return navHeight + statusBarHeight
			}
		},
		methods: {
      // 获取店铺详情
      async getQiyeDetail (shopId) {
        const { code, data, msg } = await getQiyeDetail({
          id: shopId
        })
        if (code === 200) {
          this.form = { ...this.form, ...data }
          this.form.shopType = this.shopTypeList[0].find(item => item.dictValue === data.type) || {}
          this.form.scenicArea = this.scenicAreaList[0].find(item => item.jingquId === data.jingquId) || {}
          // 经纬度
          const [longitude, latitude] = data.addressDetail.split(',')
          this.longitude = longitude
          this.latitude = latitude
          this.markers.map(marker => {
            marker.latitude = latitude
            marker.longitude = longitude
          })
          // 门脸
          this.form.frontPhotoList.push({
            status: 'success',
            message: '',
            url: data.doorImg
          })
        } else {
          this.$modal.msgError(msg)
        }
      },
      // 获取景区列表
      async getJingquList () {
        const { code, data, msg } = await getJingquList()
        if (code === 200) {
          this.scenicAreaList.splice(0, 1, data)
        } else {
          this.$modal.msgError(msg)
        }
      },
      // 获取店铺类型字典
      async getQiyeTypeList () {
        const { code, data, msg } = await getSystemDictTypeData(MERCHANT_TYPE)
        if (code === 200) {
          this.shopTypeList.splice(0, 1, data)
        } else {
          this.$modal.msgError(msg)
        }
      },
      /**
       * 判断位置授权
       */
      isGetLocation () {
        uni.getSetting({
          success: (res) => {
            console.log('获取授权信息', res)
            if (!res.authSetting[scope]) {
              this.getAuthorize(scope)
            } else {
              this.getLocation()
            }
          },
          fail: (err) => {
            console.error(err)
          }
        })
      },
      /**
       * 获取位置授权
       */
      getAuthorize() {
        uni.authorize({
          scope,
          success: (res) => {
            console.log('授权成功', res)
            this.getLocation()
          }
        })
      },
      /**
       * 获取当前位置
       */
      getLocation () {
        uni.getLocation({
          type: 'gcj02',
          success: (res) => {
            if(res.errMsg === "getLocation:ok"){
              console.log('选择位置', res)
              this.latitude= res.latitude
              this.longitude = res.longitude
              this.markers.map(item => {
                item.latitude = this.latitude
                item.longitude = this.longitude
              })
            }
          },
          error: (err) => {
            console.error('获取位置失败', err)
          }
        })
      },
      // 查看位置
      openMap () {
        uni.chooseLocation({
          latitude: this.latitude,
          longitude: this.longitude,
          success: (res) => {
            const { longitude, latitude } = res
            this.longitude = longitude
            this.latitude = latitude
            this.markers.map(marker => {
              marker.longitude = longitude
              marker.latitude = latitude
            })
          },
          fail: (err) => {
            console.error('选择位置失败', err)
          }
        })
      },
      /**
       * 选择店铺类型
       * @param event
       */
			confirmShopType (event) {
        this.form.shopType = event.value[0]
				this.showShopType = false
        this.$refs.form.validateField('shopType.dictLabel')
			},
      /**
       * 选择归属景区
       * @param event
       */
      confirmScenicArea (event) {
        this.form.scenicArea = event.value[0]
        this.showScenicArea = false
        this.$refs.form.validateField('scenicArea.jingquName')
      },
      addFrontPhoto (event) {
        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        const lists = [].concat(event.file)
        const file = lists[0]
        this.form.frontPhotoList.splice(0, 1,{
          ...file,
          status: 'uploading',
          message: '上传中'
        })
        uploadImg({
          filePath: file.url
        }).then(res => {
          const url = res.data.url
          this.form.frontPhotoList.splice(0, 1,{
            ...file,
            status: 'success',
            message: '',
            url
          })
          this.$refs.form.validateField('frontPhotoList');
        })
      },
      deleteFrontPhoto () {
        this.form.frontPhotoList.splice(0, 1)
        this.$refs.form.validateField('frontPhotoList')
      },
      /**
       * 下一步
       */
      next () {
        this.$refs.form.validate().then(res => {
          const data = {
            id: this.form.id,
            address: this.form.address,
            addressDetail: `${this.longitude},${this.latitude}`,
            applyName: this.form.applyName,
            applyPhone: this.form.applyPhone,
            businessLicenseImg: this.form.businessLicenseImg,
            businessPhone: this.form.businessPhone,
            businessTime: this.form.businessTime,
            doorImg: this.form.frontPhotoList[0].url,
            jingquId: this.form.scenicArea.jingquId,
            name: this.form.name,
            type: this.form.shopType.dictValue
          }
          uni.navigateTo({
            url: '/pages/shop/shopAuth?data=' + JSON.stringify(data)
          })
        }).catch(errors => {
          console.warn('errors', errors)
          this.$modal.msgError(errors[0].message)
        })
      }
		}
	}
</script>

<style lang="scss" scoped>
	.store_detail_page {
		width: 100vw;
		height: 100vh;
		background-color: #F3F3F3;
		.navBar {
			display: flex;
			align-items: center;
			.nav_title {
				font-size: 36rpx;
				font-weight: 400;
				color: #000000;
				margin-left: 8rpx;
			}
		}
    .steps {
      height: 64rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      .step {
        display: flex;
        align-items: center;
        text {
          font-size: 24rpx;
          font-weight: 400;
          margin-left: 8rpx;
        }
      }
      .un_active {
        ::v-deep .u-badge {
          background: #999999;
        }
        text {
          color: #999999;
        }
      }
      ::v-deep .u-icon__icon {
        margin: 0 28rpx;
        font-size: 26rpx !important;
      }
    }
		.content {
      padding: 0 16rpx;
			.card_list {
				padding-bottom: 184rpx;
			}
			.card_box {
				background-color: #fff;
				display: flex;
				flex-direction: column;
				border-radius: 16rpx;
				padding: 32rpx;
				margin-top: 16rpx;
				.card_title {
					font-size: 32rpx;
					font-weight: 500;
					color: #333333;
					& > text {
						font-size: 32rpx;
						font-weight: 400;
						color: #ED6F51;
						margin-left: 8rpx;
					}
				}
				.title_fuza {
					display: flex;
					flex-direction: column;
					.title_top {
						display: flex;
						justify-content: space-between;
						align-items: center;
						text {
							font-size: 32rpx;
							font-weight: 400;
							color: #ED6F51;
							margin-left: 8rpx;
						}
					}
					.title_bottom {
						font-size: 24rpx;
						font-weight: 400;
						color: #999999;
						margin-top: 4rpx;
					}
				}
				.card_content {
          margin-top: 40rpx;
					display: flex;
					align-items: center;
					.with_arrow {
						width: 100%;
						display: flex;
						align-items: center;
						justify-content: space-between;
					}
          ::v-deep .u-input {
            width: 100%;
            border: none !important;
            padding: 0 !important;
          }
          ::v-deep .u-form-item__body {
            padding: 0 !important;
          }
          .file_upload {
            ::v-deep .u-upload__button {
              border-radius: 16rpx;
            }
            ::v-deep .u-upload__button__text {
              margin-top: 16rpx;
              font-size: 24rpx;
              font-weight: 400;
              color: #999999;
            }
            ::v-deep .u-icon__icon {
              color: #999999 !important;
              font-size: 33rpx;
            }
          }
          .add_icon {
            margin-right: 26rpx;
            ::v-deep .u-icon__icon {
              color: #01756B !important;
            }
          }
				}
			}
		}
		.footer {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 144rpx;
			background: #FFFFFF;
      padding: 18rpx 24rpx 0;
			border: 1rpx solid #F3F3F3;
      z-index: 99;
		}
	}
</style>
